from flask import Flask, request, jsonify
import logging
import time
import team.into_team as into_team
import script as script

app = Flask(__name__)
logging.basicConfig(filename='app.log', level=logging.INFO)

@app.route('/receive_invite', methods=['POST'])
def handle_invite():
    """队员接收邀请的接口"""
    try:
        #模拟按键操作同意组队
        i = into_team.IntoTeam()
        into_flag = i.into_control()
        app.logger.info(f"进队结果{into_flag}")

        if into_flag:
            return jsonify({'success': True})
        else:
            app.logger.error(f"进队失败")
            return jsonify({'success': False})
    except Exception as e:
        app.logger.error(f"Invite error: {str(e)}")
        return jsonify({'success': False}), 400

@app.route('/confirm_join', methods=['POST'])
def handle_confirm():
    """队长接收确认的接口"""
    member_ip = request.json['member_ip']
    # 可记录日志或触发后续操作
    return jsonify({'received': True})


@app.route('/handle_start_game', methods=['POST'])
def handle_start_game():
    """队员接受队长通知已经开启游戏"""
    print(request.json)
    start_time = request.json['start_time']
    app.logger.info(f"本次开始游戏时间：{start_time}")

    # 得到队长开始时间 和 过图等待时间 统一开始
    this_time =  time.time()
    sleep_time = start_time - this_time

    sc = script.Script()
    sc.after_invite_start_game(sleep_time)



def start_flask_server(port=5000):
    from waitress import serve
    serve(app, host="0.0.0.0", port=port)

if __name__ == '__main__':
    start_flask_server()